<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import LayoutNav from '../Layout/components/LayoutNav.vue';
import LayoutFooter from '../Layout/components/LayoutFooter.vue';
import router from '@/router';
import { getOrderListAPI, updateOrderAPI } from '@/api/order';
import { getPurchaseListAPI, updatePurchaseAPI } from '@/api/purchase';
// import { payAPI } from '@/api/pay';

//获取订单信息
import { useOrderStore } from '@/store/order';
const orderStore = useOrderStore();

// 支付信息
const payInfo = ref({
  traceNo: '',
  totalAmount: '',
  subject: '',
  orderType: ''
})
const totalPrice = ref(1000);

// 获取登录用户信息
import { useTokenStore } from '@/store/token'
import { ElMessage } from 'element-plus';
import axios from 'axios';
const tokenStore = useTokenStore();

const checkInfo = ref({})  // 订单对象
checkInfo.value = orderStore.checkInfo
const goodName =ref('')
goodName.value = checkInfo.value.goodName
let data = {
  userId: tokenStore.user.userId,
  storeId: checkInfo.value.salerId,
  goodId: checkInfo.value.goodId
}
function getOrderInfo(){
  console.log('当前用户身份,',tokenStore.user.identity);
  if (tokenStore.user.identity == '0') {
    getOrderListAPI(data.userId, data.storeId, data.goodId).then(res=>{
      if(res.code === 0){
        payInfo.value.traceNo = res.data[res.data.length -1 ].orderId
        localStorage.setItem ('payOrderId', payInfo.value.traceNo)
        payInfo.value.totalAmount = res.data[res.data.length -1 ].payment
        totalPrice.value = payInfo.value.totalAmount
        payInfo.value.subject = goodName.value
        if (tokenStore.user.identity == '0') {
          payInfo.value.orderType = 'ORDER'
        } else {
          payInfo.value.orderType = 'PURCHASE'
        }
        console.log(payInfo.value);
        
      } else{
        ElMessage.error(res.message || '获取订单信息失败')
      }
    })
  } else if (tokenStore.user.identity == '1' || tokenStore.user.identity == '2') {
    let data = {
      buyerId: tokenStore.user.userId,
      sellerId: checkInfo.value.salerId,
      goodId: checkInfo.value.goodId
    }
    getPurchaseListAPI(data.buyerId, data.sellerId, data.goodId, null).then(res=>{
      if(res.code === 0){
        payInfo.value.traceNo = res.data[res.data.length -1 ].purchaseId
        localStorage.setItem ('payOrderId', payInfo.value.traceNo)
        payInfo.value.totalAmount = res.data[res.data.length -1 ].payment
        totalPrice.value = payInfo.value.totalAmount
        payInfo.value.subject = goodName.value
        if (tokenStore.user.identity == '0') {
          payInfo.value.orderType = 'ORDER'
        } else {
          payInfo.value.orderType = 'PURCHASE'
        }
        console.log(payInfo.value);
        
      } else{
        ElMessage.error(res.message || '获取订单信息失败')
      }
    })
  }
}
getOrderInfo();

const pays = ref(localStorage.getItem('pays') || 0); // 支付状态
// 支付
const paychase = async() => {
  try {
    const payData = {
      traceNo: payInfo.value.traceNo,
      totalAmount: payInfo.value.totalAmount,
      subject: payInfo.value.subject,
      orderType: payInfo.value.orderType
    }

    const res = await axios.get("http://localhost:8081/taoxi/alipay/pay", {
      params: payData,
    })
    const formHtml = res.data;

    // 创建一个临时div来插入表单
    const formContainer = document.createElement("div");
    formContainer.innerHTML = formHtml;

    // 确保表单存在
    const form = formContainer.querySelector("form");
    if (form) {
      document.body.appendChild(formContainer);
      form.submit(); // 提交表单
      localStorage.setItem('pays', 1);
      console.log('跳转支付页面,', localStorage.getItem('pays'))
    } else {
      localStorage.setItem('pays', 0);
      console.log('找不到表单,', localStorage.getItem('pays'));
    }
  } catch (error) {
    ElMessage.error(error.message || '请求支付失败')
  }
}

const handlePayStatus = () => {
  if (localStorage.getItem('pays') == 1) {
    ElMessage.success('支付成功');
    const payOrderId = localStorage.getItem('payOrderId');
    console.log('支付订单id', payOrderId);
    if (tokenStore.user.identity == '0') {
      updateOrderAPI(payOrderId, 1).then(res => {
        if (res.code === 0) {
          console.log('订单状态改为-1-待发货');
          localStorage.setItem('payOrderId', 1);
        }
      })
    } else {
      updatePurchaseAPI(payOrderId, 1).then(res => {
        if (res.code === 0) {
          console.log('采购订单状态改为-1-待发货');
          localStorage.setItem('payOrderId', 1);
        }
      })
    }

    // 清空
    localStorage.setItem('pays', 0);
    setTimeout(() => {
      router.push('/orderOk');
    }, 1000);
  } else {
    ElMessage.warning('请使用支付宝支付！')
  }
}
handlePayStatus();

const remainingTime = ref(10); // 设置初始时间为10分钟
let timer;
const updateTimer = () => {
  if (remainingTime.value > 0) {
    remainingTime.value--;
  } else {
    clearInterval(timer);
    // 可以在这里处理订单超时逻辑，比如显示提示信息或重定向
    alert('订单已超时，请重新下单！');
    router.push('/order');
  }
};
onMounted(() => {
  timer = setInterval(updateTimer, 60000); // 每分钟更新一次
});
onBeforeUnmount(() => {
  clearInterval(timer); // 清除计时器
});

</script>

<template>
    <LayoutNav></LayoutNav>
  <div class="xtx-pay-page">
    <div class="container">
      <!-- 付款信息 -->
      <div class="pay-info">
        <span class="icon iconfont icon-queren2"></span>
        <div class="tip">
          <p>订单提交成功！请尽快完成支付。</p>
          <p>支付还剩 <span>{{ remainingTime }} 分钟</span>, 超时后将取消订单</p>
        </div>
        <div class="amount">
          <span>应付总额：</span>
          <span>¥ {{ totalPrice }} </span>
        </div>
      </div>
      <!-- 付款方式 -->
      <div class="pay-type">
        <p class="head">选择以下支付方式付款（暂只支持支付宝）</p>
        <div class="item">
          <p>支付平台</p>
          <a class="btn wx" href="javascript:;"></a>
          <a @click="paychase" class="btn alipay"></a>
          <hr>
          <el-button type="cancel" @click="router.push('/')" style="margin-left: 70%;background-color: #e58686;color: #fff;">
            取消支付
          </el-button>
        </div>
      </div>
    </div>
  </div>
  <LayoutFooter></LayoutFooter>
</template>

<style scoped lang="scss">
.xtx-pay-page {
  margin-top: 20px;
  padding-bottom: 20px;
}

.pay-info {

  background: #fff;
  display: flex;
  align-items: center;
  height: 240px;
  padding: 0 80px;
  border-radius: 10px;

  .icon {
    font-size: 80px;
    color: #1dc779;
  }

  .tip {
    padding-left: 10px;
    flex: 1;

    p {
      &:first-child {
        font-size: 20px;
        margin-bottom: 5px;
      }

      &:last-child {
        color: #999;
        font-size: 16px;
      }
    }
  }

  .amount {
    span {
      &:first-child {
        font-size: 16px;
        color: #999;
      }

      &:last-child {
        color: $priceColor;
        font-size: 20px;
      }
    }
  }
}

.pay-type {
  margin-top: 20px;
  background-color: #fff;
  padding-bottom: 70px;
  border-radius: 10px;

  p {
    line-height: 70px;
    height: 70px;
    padding-left: 30px;
    font-size: 16px;

    &.head {
      border-bottom: 1px solid #f5f5f5;
    }
  }

  .btn {
    width: 150px;
    height: 50px;
    border: 1px solid #e4e4e4;
    text-align: center;
    line-height: 48px;
    margin-left: 30px;
    color: #666666;
    display: inline-block;

    &.active,
    &:hover {
      border-color: $xtxColor;
    }

    &.alipay {
      background: url(https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/7b6b02396368c9314528c0bbd85a2e06.png) no-repeat center / contain;
    }

    &.wx {
      background: url(https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/c66f98cff8649bd5ba722c2e8067c6ca.jpg) no-repeat center / contain;
    }
  }
}
</style>